//
//  ReplyViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/9/23.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "ReplyViewController.h"
#import "TPKeyboardAvoidingScrollView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#include <CommonCrypto/CommonCrypto.h>
#import "MWPhotoBrowser.h"
#import "CQiniuFileUpload.h"
#import "QNUploadOption.h"
#import "UIImage+ResizeMagick.h"

@interface ReplyViewController ()<UITextViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    TPKeyboardAvoidingScrollView *_scrollView;
    NSMutableDictionary *_dic;
    UIImageView *_imgView;
    BOOL _isSelectOriginalPhoto;
    NSMutableArray *_numAr;
    UIView *_delView;
    UIImageView *_delImg;



}
@property (nonatomic, strong) UITextView *txtView;
@property (nonatomic) BOOL isReplay;

@end

@implementation ReplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"回复任务详情"];
    self.isReplay=YES;
    __block typeof(self) blockself = self;

    [self.navBar setBackAction:^{
        if(([_txtView.text isEqualToString:@"输入你的回复..."]||[_txtView.text isEqualToString:@""])&&_numAr.count==0)
        {
            [blockself backController];
            
        }else
        {
            [CClass showAlertTitle:nil hidden:NO context:@"离开后内容丢失。是否离开？" oneBtn:@"离开" twoBtn:@"取消" handler:^{
                [blockself backController];

            }handler:^{
                
            }];
        }

    }];

    
    
    _dic = [[NSMutableDictionary alloc]init];
    _numAr =[[NSMutableArray alloc]init];
    [self.navBar createRightBtn:@"发送" block:^{
        [self.view endEditing:YES];
        if (_txtView.text.length >200) {
            [CClass showMessage:@"您最多可以输入200个字"];
            return;
        }
        if (([_txtView.text isEqualToString:@"输入你的回复..."]||[_txtView.text isEqualToString:@""])&&_numAr.count==0) {
            [CClass showMessage:@"请输入回复内容！"];
            return;
            
        }


        if([_txtView.text isEqualToString:@"输入你的回复..."]||[_txtView.text isEqualToString:@""])
        {
            [_dic setObject:@"" forKey:@"describe"];

        }else
        {
            [_dic setObject:_txtView.text forKey:@"describe"];

        }
        
        [_dic setObject:self.orderUuid forKey:@"orderUuid"];
        if (self.isReplay==YES) {
            self.isReplay=NO;
            
            if(_numAr.count>0)
            {
                //图片 上传图片
                NSString *imgName = [NSString stringWithFormat:@"%@_%@.jpg", [Common getDateTimeString], [Common randomStringWithLength:8]];
                NSData *data =[_imgView.image resizedAndReturnData];
                
                [_dic setObject:imgName forKey:@"image"];
                
                [self setIsLoading:YES];
                
                [[CQiniuFileUpload uploadFile]uploadFiles:[CFileModel initWithFile:data name:imgName] progress:^(CFileUpload *upload, float per) {
                    
                } finish:^(CFileUpload *upload, NSArray *models, NSError *error) {
                    //成功之后发送
                    
                    [CClass HttpRequestTask:YES withUrl:@"warning_orderMessageBoard" withData:_dic notifyError:YES onSuccess:^(BaseModel *model) {
                        [CClass showLittleTimeMessage:@"回复成功" completion:^{
                            [self setIsLoading:NO];
                            [self backController];
                            
                            
                        }];
                    } onError:^(BaseModel *model) {
                        self.isReplay=YES;
                        [self setIsLoading:NO];

                    }];
                    
                }];
                
            
        }else
        {
            [self setIsLoading:YES];
            [_dic setObject:@"" forKey:@"image"];
            [CClass HttpRequestTask:YES withUrl:@"warning_orderMessageBoard" withData:_dic notifyError:YES onSuccess:^(BaseModel *model) {
                [CClass showLittleTimeMessage:@"回复成功" completion:^{
                    [self backController];
                    [self setIsLoading:NO];
                    
                }];
            } onError:^(BaseModel *model) {
                self.isReplay=YES;
                [self setIsLoading:NO];

            }];
        }
        
            
        

        }
        
        
        }];
    

    
    _scrollView =[[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, 64, WindowWidth,WindowHeight-64)];
    _scrollView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_scrollView];
    //输入框
    UIView *bgView =[[UIView alloc]initWithFrame:CGRectMake(15, 0, WindowWidth-30, 200)];
    bgView.backgroundColor =[UIColor whiteColor];
    [_scrollView addSubview:bgView];
    [bgView addSubview:self.txtView];
    _txtView = [[UITextView alloc] init];
    [_txtView setDelegate:self];
    [_txtView setText:@"输入你的回复..."];
    [_txtView setTextColor:C(@"cbcbcb")];
    _txtView.font =F(11);
    [_txtView setTextContainerInset:UIEdgeInsetsMake(5, 0, 5, 0)];
    [bgView addSubview:_txtView];
    [self.txtView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView).mas_offset(0);
        make.right.equalTo(bgView).mas_offset(0);
        make.top.equalTo(bgView).mas_offset(5);
        make.bottom.equalTo(bgView).mas_offset(-5);
    }];
    UIImage *image =[UIImage imageNamed:@"AlbumAddBtn"];
    _imgView=[[UIImageView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(bgView.frame)+10, image.size.width, image.size.height)];
    
    _imgView.image =image;
    _imgView.userInteractionEnabled=YES;
    [_imgView bk_whenTapped:^{
        [_txtView resignFirstResponder];
        if (_numAr.count>0) {
            
            
            //            //预览图片
            //预览图片
            [XWScanImage scanBigImageWithImageView:_imgView];
        }else
        {
            [self chooseClick];

        }
        
        
    }];
    [_scrollView addSubview:_imgView];
    UIImage *imgdel = [UIImage imageNamed:@"Ico_detail_delete"];
    _delView = [[UIButton alloc] initWithFrame:CGRectMake(_imgView.bounds.size.width- 30, 0, 30, 30)];
    _delView.backgroundColor=[UIColor clearColor];
    [_delView bk_whenTapped:^{
        [_numAr removeAllObjects];
        _delView.hidden=YES;
        _imgView.image=[UIImage imageNamed:@"AlbumAddBtn"];
        
    }];
    [_delView setHidden:YES];
    [_imgView addSubview:_delView];

    _delImg=[[UIImageView alloc]initWithFrame:CGRectMake(30-imgdel.size.width, 0, imgdel.size.width, imgdel.size.height)];
    [_delView addSubview:_delImg];
    _delImg.userInteractionEnabled=YES;
    _delImg.image=imgdel;
   
   
}


- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"输入你的回复..."]) {
        [textView setText:@""];
        [textView setTextColor:C(@"000000")];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    
    return _numAr.count;
}
- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.markedTextRange == nil && textView.text.length > 200)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
        
    {
        
        textView.text = [textView.text substringToIndex:200];
        
    }
    
}
#pragma mark -- 打开系统相册
-(void)chooseClick{
    UIActionSheet *sheet;
    
    //判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"拍照", @"从相册中选取", nil];
    }else{
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"从相册中选取", nil];
    }
    sheet.actionSheetStyle=UIActionSheetStyleBlackOpaque;
    sheet.tag = 200;
    [sheet showInView:self.view];
}
#pragma mark -- 判断是否支持相机 ，跳转到相机 或相册界面
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 200){
        NSInteger sourceType = 0;
        //判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            switch (buttonIndex){
                case 0:
                    //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    //取消
                    return;
                    break;
                default:
                    break;
            }
        }else{
            if (buttonIndex == 0){
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }else if(buttonIndex==1){
                return;
            }
        }
        
        //跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        imagePickerController.allowsEditing = NO;
        //状态栏变成白色
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    navigationController.navigationBar.translucent = NO;
    [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication  sharedApplication]  setStatusBarHidden:NO];
}

#pragma mark -- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        picker.allowsEditing=YES;
        // _headImg.image = image;
        //设置image的尺寸
        //初始化imageNew为从相机中获得的-- 压缩
        UIImage *imageNew = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData=  [CClass compressImageQuality:imageNew];
        
        _imgView.image=[UIImage imageWithData:imageData];
        [_numAr addObject:[MWPhoto photoWithImage:[UIImage imageWithData:imageData]]];
        _delView.hidden=NO;
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        
    });
}


-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

@end
